<template>
  <div class="table-classic-wrapper">
    <el-card shadow="always">

      <!--搜索栏 -->
      <el-row style="margin-bottom: 10px;">
        <el-col :span="24">

          <el-form
              :inline="true"
              class="search-form">

            <el-form-item>
              <el-input placeholder="请输入美食名称" v-model="searchForm.text" style="width: 280px;">
                <i slot="suffix" class="el-input__icon el-icon-search"
                   @click="searchCommodityByText()"></i>
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="danger" icon="el-icon-search" @click="getCommodityList">
                查询全部美食
              </el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="el-icon-plus" @click="dialogVisibleAddCommodity=true">
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <!--美食列表-->
      <el-table
          :data="commodityList"
          stripe
          style="width: 100%;"
          :header-cell-style="{textAlign: 'center'}"
          @selection-change="handleSelectionChange"
          :cell-style="{textAlign: 'center'}"
          class="table-inline-edit">

        <el-table-column type="selection" width="50"/>

        <el-table-column
            prop="picture"
            label="美食图片"
            align="center">
          <template slot-scope="scope">
            <el-image
                style="width: 40px; height: 40px"
                :src="handlerImg(scope.row.picture)"
                fit="fill"
                ></el-image>
          </template>
        </el-table-column>

        <el-table-column
            label="美食名称">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>美食名称: {{ scope.row.text }}</p>
              <p>美食类别: {{ scope.row.type }}</p>
              <p>美食在售数量: {{ scope.row.saleCount }}</p>
              <p>美食历史销量: {{ scope.row.historicalSaleCount }}</p>
              <div slot="reference">
                <el-tag size="medium">{{ scope.row.text }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
            prop="type"
            label="美食类别">
        </el-table-column>

        <el-table-column
            prop="price"
            label="美食价格">
        </el-table-column>

        <el-table-column
            prop="saleCount"
            label="库存"
            align="center">
        </el-table-column>

        <el-table-column
            prop="historicalSaleCount"
            label="历史销量"
            align="center">
        </el-table-column>

        <el-table-column
            prop="peopleBuy"
            label="购买人数"
            align="center">
        </el-table-column>

        <el-table-column
            prop="product_state"
            label="美食状态"
            align="center">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.productState===0" effect="plain">待售</el-tag>
            <el-tag type="warn" v-if="scope.row.productState===1" effect="plain">已下架</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="评价分数">
          <template slot-scope="scope">
            <el-rate
                v-model="scope.row.appraiseScore"
                disabled
                show-score
                text-color="#ff9900">
            </el-rate>
          </template>
        </el-table-column>

        <el-table-column
            prop="auditState"
            label="美食审核状态"
            align="center">
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.auditState===0" effect="plain">待审核</el-tag>
            <el-tag type="success" v-if="scope.row.auditState===1" effect="plain">已发布</el-tag>
            <el-tag type="primary" v-if="scope.row.auditState===2" effect="plain">审核未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" :disabled="forbidByAdministrator(scope.row)"
                       @click="editHandle(scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <Pagination :total="total" :page="currentPage" :limit="pageSize" @pagination="handlePageChange"></Pagination>
    </el-card>

    <!--新增美食对话框-->
    <el-dialog
        title="新增美食"
        :visible.sync="dialogVisibleAddCommodity"
        :before-close="handleClose"
        width="30%">
      <el-form :model="addCommodityForm" :rules="addCommodityRules" ref="refForm" label-width="80px">
        <el-form-item label="美食名称" prop="text">
          <el-input v-model="addCommodityForm.text" style="width: 320px" size="medium" placeholder="填写美食名称"
                    clearable></el-input>
        </el-form-item>

        <el-form-item label="美食类别" prop="type">
          <el-select v-model="addCommodityForm.type" placeholder="请选择">
            <el-option label="徽菜" value="徽菜"></el-option>
            <el-option label="鲁菜" value="鲁菜"></el-option>
            <el-option label="闽菜" value="闽菜"></el-option>
            <el-option label="湘菜" value="湘菜"></el-option>
            <el-option label="川菜" value="川菜"></el-option>
            <el-option label="江苏菜" value="江苏菜"></el-option>
            <el-option label="粤菜" value="粤菜"></el-option>
            <el-option label="浙江菜" value="浙江菜"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="美食价格" prop="price">
          <el-input v-model="addCommodityForm.price" style="width: 140px;" size="medium" placeholder="填写美食价格"
                    clearable></el-input>
          ￥
        </el-form-item>
        <el-form-item label="美食图片" prop="picture">
          <el-upload
              action="#"
              list-type="picture-card"
              multiple
              ref="upload"
              :file-list="addCommodityForm.picture"
              accept="image/jpg, image/png, image/jpeg"
              :on-change="HandleChange"
              :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div slot="tip" class="el-upload__tip">只能上传.jpg、.png、.jpeg文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="美食状态" prop="sale_state">
          <div>
            <el-radio-group v-model="addCommodityForm.product_state" size="small">
              <el-radio-button label='0'>待售</el-radio-button>
              <el-radio-button label='1'>已下架</el-radio-button>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="在售数量" prop="sale_count">
          <el-input-number size="small" :min="1" v-model="addCommodityForm.sale_count"></el-input-number>
        </el-form-item>

        <el-form-item style="text-align: right">
          <el-button @click="handleClose" size="medium">取 消</el-button>
          <el-button type="primary" @click="addCommodity" size="medium">提 交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--
      新增/编辑 弹出栏
      visible：是否显示 Dialog，支持.sync修饰符
      -->
    <el-dialog
        title="编辑"
        :visible.sync="formVisible"
        width="30%"
        :before-close="handleClose">
      <el-form
          ref="updateForm"
          :model="updateForm"
          :rules="updateRules"
          label-width="100px">

        <el-form-item
            label="库存：">
          <el-input-number
              v-model="updateForm.saleCount"
              size="mini" :min="0">
          </el-input-number>
        </el-form-item>

        <el-form-item label="美食价格：" prop="price">
          <el-input v-model="updateForm.price" style="width: 140px;" size="medium" placeholder="填写美食价格"
                    clearable></el-input>
          ￥
        </el-form-item>

        <el-form-item label="美食状态" prop="sale_state">
          <div>
            <el-radio-group v-model="updateForm.saleState" size="small">
              <el-radio-button label='0'>待售</el-radio-button>
              <el-radio-button label='1'>已下架</el-radio-button>
            </el-radio-group>
          </div>
        </el-form-item>


        <div class="footer-item">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm('updateForm')">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>


import {upload} from "@/api/merchant/commodity/file";
import {getUserInformation} from "@/api/user";
import {
  getCommodityByPagination,
  getCommodityByTextCurrentMerchant,
  updateMerchantCommodity,
} from "@/api/merchant/commodity/commodity";
import Pagination from "@/component/pagination/Pagination";
import {getGeneralUserById} from "@/api/general/userGeneral";

export default {
  name: "CommodityManagement",
  components: {
    Pagination
  },
  data() {
    return {

      /**
       * 新增美食对话框显示
       */
      dialogVisibleAddCommodity: false,

      /**
       * option：选项
       */
      option: 0,

      total: 0,//美食总数
      currentPage: 0,//当前页码
      pageSize: 8,//每页显示条数

      originalTotal: 0,//原始的美食总数

      /*
      * 多选数据暂存数组
      */
      multipleSelection: [],

      /**
       * 搜索内容
       */
      searchForm: {
        text: '',//搜索框中输入的美食名称
      },

      /**
       * addCommodityForm：新增美食的属性名
       */
      addCommodityForm: {
        price: '',//美食价格
        type: '',//美食类别
        picture: [],//美食图片
        text: '',//美食名称
        sale_count: '',//美食在售数量
        product_state: 0,//美食状态 0：待售；1：已下架
        /**
         * 新增美食时所需要的初始值
         */
        historical_sale_count: 0,//历史销量，初始值为0
        people_buy: 0,//购买人数，初始值为0
        appraise_score: 0,//对美食的评价分数，初始值为0
        trading_count: 0,//交易数量，初始值为0
        audit_state: 0,//审核状态，0--待审核，1--已发布，2--审核未通过

        userId: 0,//该美食对应的商家用户id
      },

      /**
       * 美食信息列表
       */
      commodityList: [],

      /**
       * 添加美食规则
       */
      addCommodityRules: {
        text: [{required: true, trigger: 'blur', message: '名称不能为空'},
          {min: 2, max: 12, message: '长度为2到12位'}],
        price: [{required: true, trigger: 'blur', message: '价格不能为空'},
          {
            pattern: /^[0-9]\d*(\.)?[0-9]\d*$/,
            message: '价格输入格式不正确'
          }
        ],
        type: [{required: true, trigger: 'blur', message: '美食类别不能为空'}]
      },

      /**
       * 当前用户
       */
      user: undefined,

      /**
       * 更新列表
       */
      updateForm: {
        id: undefined,
        saleCount: undefined,
        saleState: undefined,
        price: undefined,
        appraiseScore: undefined
      },

      /**
       * 更新美食规则
       */
      updateRules: {
        price: [{required: true, trigger: 'blur', message: '价格不能为空'},
          {
            pattern: /^[0-9]\d*(\.)?[0-9]\d*$/,
            message: '价格输入格式不正确'
          }
        ],
      },

      /*
       * 新增/编辑 弹出框显示/隐藏
       */
      formVisible: false,
    }
  },

  created() {
    this.getGeneralUserById();
  },

  methods: {
    /**
     * 获得用户信息
     */
    getGeneralUserById() {
      const user = eval('(' + getUserInformation() + ')');

      const formData = new FormData();

      formData.append("id", user.id);

      getGeneralUserById(formData).then(res => {
        this.user = res.user;
        this.getCommodityList();
        this.addCommodityForm.userId = this.user.id;
      }).catch(() => {
        this.$message.error("用户信息获取失败");
      })
    },

    /**
     * 获得该商家的美食列表
     */
    getCommodityList() {
      const formData = new FormData();

      formData.append("currentPage", this.currentPage);
      formData.append("pageSize", this.pageSize);
      formData.append("userId", this.user.id);

      getCommodityByPagination(formData).then(res => {
        this.commodityList = res.commodities;
        this.total = res.total;
        this.originalTotal = this.total;
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })
    },

    /**
     * 提交新增美食申请
     */
    addCommodity() {
      this.$refs.refForm.validate(valid => {
        const formData = new FormData();

        formData.append("price", this.addCommodityForm.price); //美食价格
        formData.append("type", this.addCommodityForm.type); //美食类别
        formData.append("picture", this.addCommodityForm.picture[0].raw); //美食图片
        formData.append("text", this.addCommodityForm.text); //美食名称
        formData.append("saleCount", this.addCommodityForm.sale_count); //美食在售数量
        formData.append("saleState", this.addCommodityForm.product_state); //0：待售；1：已下架
        formData.append("historicalSaleCount", this.addCommodityForm.historical_sale_count); //历史销量，初始值为0
        formData.append("peopleBuy", this.addCommodityForm.people_buy); //购买人数，初始值为0
        formData.append("appraiseScore", this.addCommodityForm.appraise_score); //对美食的评价分数，初始值为0
        formData.append("tradingCount", this.addCommodityForm.trading_count); //交易数量，初始值为0
        formData.append("auditState", this.addCommodityForm.audit_state); //审核状态，0--待审核，1--已发布，2--审核未通过
        formData.append("userId", this.addCommodityForm.userId);//该美食对应的商家用户id

        if (valid) {
          upload(formData).then(res => {
            if (res.message === 1) {
              this.$message({
                type: 'success',
                message: '成功添加美食'
              });
              this.getCommodityList();
              this.dialogVisibleAddCommodity = false;
            } else {
              this.$message({
                type: 'error',
                message: '添加美食失败'
              })
            }
          });
        } else {
          this.$message.error("error!");
        }
      });
      this.handleClose()
    },

    /**
     * 通过美食名称进行搜素
     */
    searchCommodityByText() {
      if (this.searchForm.text === '') {
        this.$message({
          message: "请输入美食名称",
          type: "warning"
        });
        this.commodityList = [];
        this.total = 0;
      } else {
        const formData = new FormData();
        formData.append("currentPage", this.currentPage);
        formData.append("pageSize", this.pageSize);
        formData.append("text", this.searchForm.text);
        formData.append("userId", this.user.id);

        getCommodityByTextCurrentMerchant(formData).then(res => {
          this.commodityList = res.commodities;
          this.total = res.total;
        }).catch(() => {
          this.$message({
            message: "error",
            type: "error"
          })
        })
      }
      this.searchForm.text = ''
    },

    /**
     * 关闭对话框前的回调
     */
    handleClose() {
      this.dialogVisibleAddCommodity = false;
      this.formVisible = false;
      this.$refs.refForm.resetFields();
      this.$refs.updateForm.resetFields();
    },

    /**
     *事件改变触发的事件
     */
    HandleChange(file, fileList) {
      this.addCommodityForm.picture = fileList.slice(-1);//文件对象
    },

    /*
    * 多选操作，与multipleSelection相对应
    */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * 展示图片（获取图片在服务器中的路径）
     */
    handlerImg(picture){
      console.log("data:image/jpeg;base64," + picture)
      return "data:image/jpeg;base64," + picture

    },

    /**
     * 处理分页
     */
    handlePageChange(val) {
      this.currentPage = val.page;
      if(this.total===this.originalTotal){
        this.getCommodityList();
      }else {
        this.searchCommodityByText();
      }
    },

    /**
     * 编辑操作
     */
    editHandle(row) {
      this.updateForm.id = row.id;
      this.updateForm.saleCount = row.saleCount;
      this.updateForm.saleState = row.productState;
      this.updateForm.price = row.price;
      this.updateForm.appraiseScore = row.appraiseScore;
      this.formVisible = true;
    },

    /**
     * 编辑表单提交
     */
    submitForm() {
      const dataForm = new FormData();
      dataForm.append("id", this.updateForm.id);
      dataForm.append("saleState", this.updateForm.saleState);
      dataForm.append("price", this.updateForm.price);
      dataForm.append("saleCount", this.updateForm.saleCount);
      dataForm.append("appraiseScore", this.updateForm.appraiseScore);
      dataForm.append("userId", this.user.id);
      dataForm.append("currentPage", this.currentPage);
      dataForm.append("pageSize", this.pageSize);

      this.modifyMerchantCommodity(dataForm);

      this.formVisible = false;
    },

    /**
     * 修改指定美食的信息
     */
    modifyMerchantCommodity(dataForm) {
      updateMerchantCommodity(dataForm).then(res => {
        this.commodityList = res.commodities;
        this.total = res.total;
      }).catch(() => {
        this.$message({
          message: "error",
          type: "error"
        })
      })
    },

    /**
     * 针对该美食是否被管理员下架进行操作
     */
    forbidByAdministrator(row) {
      return row.offShelf === 1;
    }

  },
}
</script>

<style scoped>
@import "../../../assets/less/merchant/commodity/card.less";

</style>
